package main

import (
	"database/sql"
	"encoding/json"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

func main() {
	//db是延迟创建的，此时如果参数有误并不会保存
	db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/db1")
	if err != nil {
		log.Fatal(err)
	}
	//测试数据库连接
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	//sql := "INSERT INTO miao(cnt, version) VALUE(3,1)"
	//insert(db, sql)

	sql := "UPDATE miao SET cnt = 1, version = 3 WHERE id = 5"
	update(db, sql)

	sql = "SELECT * FROM miao"
	selectData(db, sql)
}

type Miao struct {
	Id      int
	Cnt     int
	Version int
}

func selectData(db *sql.DB, sql string) []Miao {
	rows, err := db.Query(sql)
	defer rows.Close()
	if err != nil {
		log.Fatalf("select error %v\n", err)
	}
	var res []Miao
	for rows.Next() {
		var m Miao
		rows.Scan(&m.Id, &m.Cnt, &m.Version)
		if err != nil {
			log.Fatal(err)
		}
		json, _ := json.Marshal(m)
		log.Printf("get data, %v\n", string(json))
		res = append(res, m)
	}

	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}
	return res
}

func insert(db *sql.DB, sql string) {
	res, err := db.Exec(sql)
	if err != nil {
		log.Fatalf("insert error %v\n", err)
	}

	affected, _ := res.RowsAffected()
	log.Printf("insert rows %v\n", affected)
}

func update(db *sql.DB, sql string) {
	res, err := db.Exec(sql)
	if err != nil {
		log.Fatalf("update error %v\n", err)
	}
	affected, _ := res.RowsAffected()
	log.Printf("update rows %v\n", affected)
}
